import { StyleSheet, Text, View, ScrollView, TouchableOpacity, Pressable } from 'react-native';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import FastImage from '@d11/react-native-fast-image';
import LinearGradient from 'react-native-linear-gradient';
import { useRoute, useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import { getDeviceDetails, checkVersion } from '~/api/deviceApi';
import { getWuXueCourseApi, getDeviceBindBodyList } from '~/api/acupoints';
import { FocusAwareStatusBar, RefreshButton, DialogModal } from '~/components';
import { yjhDevices } from '~/utils/deviceMenues';
import { isIos, onePx, px2dp, scale, width } from '~/utils/px2dp';
import { observer, userStore, webSocketStore, deviceStore } from '~/store';
import BleConnection from '~/utils/ble/connect';
import { getDeviceStatus, getDeviceVersion, startUpdate } from '~/utils/socketMessenger';

const Bleconnect = BleConnection.getInstance();
export default observer(() => {
    const { t } = useTranslation();
    const router: any = useRoute();
    const { device_sn, course_id = '', title_id = '', yyDevicesn = '' } = router.params || {};
    const navigation: any = useNavigation();
    const { device_online, firmware_version, progress } = webSocketStore;
    const [deviceInfo, setDeviceInfo] = useState<any>({});
    const getData = () => {
        getDeviceDetails({ device_sn: device_sn }).then((res) => {
            if (res.status == 1) {
                const data = res.data;
                data.num = data.device_sn.substring(device_sn.length - 3);
                if (yjhDevices.indexOf(data.device_code) == -1) {
                    getWuXueCourse();
                } else {
                    getDeviceStatus(device_sn);
                    setTimeout(() => {
                        getDeviceVersion(device_sn); // 获取设备版本
                    }, 1200);
                    Bleconnect.scan();
                }
                setDeviceInfo(data);
            } else {
                if (res.msg == '设备不存在,请联系客服!') {
                    Toast.show({ content: t('AddDeviceScreen.t2'), layout: 'top' });
                } else {
                    Toast.show({ content: res.msg });
                }
            }
        });
    };
    // 获取小包数据
    const [parameterList, setParameterList] = useState([]);
    const getWuXueCourse = () => {
        getWuXueCourseApi({ course_id, id: 0 }).then((res) => {
            setParameterList(res.parameter_list);
        });
    };
    const [deviceList, setDeviceList] = useState([]);
    const getBindDeviceXueWei = async () => {
        try {
            const res = await getDeviceBindBodyList({ title_id });
            if (res.status !== 1) {
                return;
            }
            setDeviceList(res.list);
        } catch (error) {}
    };
    const reportData = () => {
        if (deviceList.length < 5) return Toast.show({ content: t('Acupoints.t58'), layout: 'top' });
        const newArray = deviceList.map((item: any, index) => {
            return { course_id: item.course_id, device_id: item.device_id };
        });
        navigation.navigate('DeviceDateView', {
            category: 'acupoint',
            acupointParams: JSON.stringify(newArray),
        });
    };

    const timesArray = [
        { end_time: '01:00', start_time: '23:00', title: t('Acupoints.t29'), content: t('Acupoints.t30') },
        { end_time: '03:00', start_time: '01:00', title: t('Acupoints.t31'), content: t('Acupoints.t32') },
        { end_time: '05:00', start_time: '03:00', title: t('Acupoints.t33'), content: t('Acupoints.t34') },
        { end_time: '07:00', start_time: '05:00', title: t('Acupoints.t35'), content: t('Acupoints.t36') },
        { end_time: '09:00', start_time: '07:00', title: t('Acupoints.t37'), content: t('Acupoints.t38') },
        { end_time: '11:00', start_time: '09:00', title: t('Acupoints.t39'), content: t('Acupoints.t40') },
        { end_time: '13:00', start_time: '11:00', title: t('Acupoints.t41'), content: t('Acupoints.t42') },
        { end_time: '15:00', start_time: '13:00', title: t('Acupoints.t43'), content: t('Acupoints.t44') },
        { end_time: '17:00', start_time: '15:00', title: t('Acupoints.t45'), content: t('Acupoints.t46') },
        { end_time: '19:00', start_time: '17:00', title: t('Acupoints.t47'), content: t('Acupoints.t48') },
        { end_time: '21:00', start_time: '19:00', title: t('Acupoints.t49'), content: t('Acupoints.t50') },
        { end_time: '23:00', start_time: '21:00', title: t('Acupoints.t51'), content: t('Acupoints.t52') },
    ];
    const getTitleAndContentByTime = (time) => {
        return (
            timesArray.find((item) => {
                const start = item.start_time;
                const end = item.end_time;
                if (start < end) {
                    return time >= start && time < end;
                } else {
                    return time >= start || time < end;
                }
            }) || {}
        );
    };
    // 替换设备
    const replaceDevice = () => {
        if (deviceStore.device.deviceStatus === 0) {
            Toast.show({ content: t('Acupoints.t18'), layout: 'top' });
            return;
        }
        navigation.navigate('ReplaceDevice', { device_sn });
    };
    // 替换手表
    const replaceWatch = () => {
        navigation.navigate('AddDeviceScreen', { device_sn: yyDevicesn, titleId: title_id });
    };
    // 呼叫设备
    const callDevice = () => {
        if (device_online == 0) {
            Toast.show({ content: t('AcupoinDeviceDetailes.t6'), layout: 'top' });
            return;
        }
        const params = {
            device_sn: device_sn,
            user_name: userStore.me.armarium_science_user_name || '',
            to_uid: userStore.me.user_id,
        };
        navigation.navigate('CallDevice', params);
    };

    const wifiPage = () => {
        if (deviceStore.device.deviceStatus == 0) {
            Toast.show({ content: t('Acupoints.t18'), layout: 'top' });
            return;
        }
        const searchDevices = deviceStore.device.searchDevices || [];
        const matchedDevice = searchDevices.find((device) => device.device_sn == device_sn) || {
            device_sn: '',
            id: '',
        };
        if (matchedDevice.device_sn) {
            deviceStore.connectBle(matchedDevice, (res) => {
                if (res.status == 2) {
                    Toast.show({ content: t('ScanDeviceResult.t8') });
                    return;
                }
                navigation.navigate('DeviceWifi', { device_sn, actionType: 'network' });
            });
        } else {
            Toast.show({ content: t('AcupoinDeviceDetailes.t19'), layout: 'top' });
        }
    };

    // 检测设备版本
    const [isUpdate, setIsUpdate] = useState(false);
    const [versionInfo, setVersionInfo] = useState({ node: '', version_sn: '' });
    const [visible, setVisible] = useState(false);
    const getCheckVersion = () => {
        if (device_online == 1) {
            checkVersion({ firmware_code: deviceInfo.device_code, version_sn: firmware_version }).then((res) => {
                if (res.status == 1) {
                    setIsUpdate(true);
                    setVersionInfo(res.data);
                } else {
                    setIsUpdate(false);
                }
            });
        }
    };
    useEffect(() => {
        getData();
        if (title_id) {
            getBindDeviceXueWei();
        }
    }, []);
    useEffect(() => {
        if (device_online == 1 && firmware_version) {
            getCheckVersion(); // 设备版本升级
        }
    }, [device_online, firmware_version]);
    return (
        <View style={styles.container}>
            <FocusAwareStatusBar translucent />
            <LinearGradient
                style={styles.container}
                colors={['rgba(37, 200, 200, 0.59)', '#fff']}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}>
                <View style={[styles.nav, styles.row]}>
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={() => {
                            navigation.goBack();
                        }}>
                        <Icon name="chevron-back-outline" size={px2dp(50)} color={'#fff'}></Icon>
                    </TouchableOpacity>
                    <Text style={styles.navtitle}>{t('AcupoinDeviceDetailes.title')}</Text>
                    <View />
                </View>

                <ScrollView contentContainerStyle={styles.contentContainerStyle} showsVerticalScrollIndicator={false}>
                    <View style={styles.deviceInfo}>
                        <FastImage
                            style={styles.yy01}
                            source={{
                                uri: deviceInfo?.device_image,
                                priority: FastImage.priority.high,
                            }}
                            resizeMode={FastImage.resizeMode.contain}
                        />
                        {yjhDevices.indexOf(deviceInfo.device_code) == -1 && (
                            <Text style={styles.use_course_name}>{deviceInfo?.use_course_name}</Text>
                        )}
                        <Text style={styles.device_sn}>
                            {t('AcupoinDeviceDetailes.t11')}：{device_sn}
                        </Text>
                        {yjhDevices.indexOf(deviceInfo.device_code) !== -1 && (
                            <View
                                style={[
                                    styles.active_border,
                                    device_online == 0 && { backgroundColor: '#e8e8e8' },
                                    { alignSelf: 'center', marginTop: px2dp(24) },
                                ]}>
                                <Text style={[styles.active_border_text, device_online == 0 && { color: '#a4a4a4' }]}>
                                    {device_online == 1
                                        ? t('AcupoinDeviceDetailes.t20')
                                        : t('AcupoinDeviceDetailes.t21')}
                                </Text>
                            </View>
                        )}
                    </View>
                    {yjhDevices.indexOf(deviceInfo.device_code) !== -1 && (
                        <View style={[styles.card, { marginTop: px2dp(24) }]}>
                            <View style={[styles.row, styles.between]}>
                                <Text style={styles.card_title}>{t('AcupoinDeviceDetailes.t22')}</Text>
                                <RefreshButton
                                    onRefresh={() => {
                                        getDeviceVersion(device_sn); // 获取设备版本
                                        setTimeout(() => {
                                            getCheckVersion();
                                        }, 1200);
                                    }}
                                />
                            </View>
                            <View style={[styles.row, { marginTop: px2dp(24) }]}>
                                <Text style={styles.version}>
                                    {t('AcupoinDeviceDetailes.t23')}：{device_online == 1 ? firmware_version : '-'}
                                </Text>
                                {isUpdate && (
                                    <Text style={[styles.version, { marginLeft: px2dp(32) }]}>
                                        {t('AcupoinDeviceDetailes.t24')}：V{versionInfo?.version_sn}
                                    </Text>
                                )}
                            </View>
                            {isUpdate && (
                                <Text style={[styles.version, { marginTop: px2dp(12), marginBottom: px2dp(32) }]}>
                                    {versionInfo?.node}
                                </Text>
                            )}
                            {isUpdate && (
                                <View style={[styles.between, styles.row]}>
                                    <Pressable style={styles.updateBt} onPress={() => setVisible(true)}>
                                        <Text style={[styles.bt_text, { color: '#fff' }]}>
                                            {t('AcupoinDeviceDetailes.t25')}
                                        </Text>
                                    </Pressable>
                                    {progress > 0 && (
                                        <View style={styles.row}>
                                            <Icon name={'arrow-up-circle'} size={px2dp(38)} color={'#626262'}></Icon>
                                            {progress == 100 ? (
                                                <Text style={styles.version}>{t('AcupoinDeviceDetailes.t26')}</Text>
                                            ) : (
                                                <Text style={styles.version}>
                                                    {t('AcupoinDeviceDetailes.t27')}
                                                    {progress}%
                                                </Text>
                                            )}
                                        </View>
                                    )}
                                </View>
                            )}
                        </View>
                    )}
                    <View style={styles.card}>
                        <Text style={styles.card_title}>{t('AcupoinDeviceDetailes.t2')}</Text>
                        {yjhDevices.indexOf(deviceInfo.device_code) !== -1 ? (
                            <View style={[styles.info]}>
                                <View style={[styles.row]}>
                                    <Pressable style={styles.item} onPress={callDevice}>
                                        <View style={styles.imgbox}>
                                            <FastImage
                                                style={styles.icons1}
                                                source={{
                                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2023/11/4e62d202311061625351306.png',
                                                    priority: FastImage.priority.high,
                                                }}
                                                resizeMode={FastImage.resizeMode.contain}
                                            />
                                        </View>
                                        <Text style={styles.title}>{t('AcupoinDeviceDetailes.t14')}</Text>
                                    </Pressable>
                                    <Pressable style={styles.item} onPress={wifiPage}>
                                        <View style={styles.imgbox}>
                                            <FastImage
                                                style={styles.icons}
                                                source={{
                                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/04/89049202504021711399597.png',
                                                    priority: FastImage.priority.high,
                                                }}
                                                resizeMode={FastImage.resizeMode.contain}
                                            />
                                        </View>
                                        <Text style={styles.title}>{t('AcupoinDeviceDetailes.t18')}</Text>
                                    </Pressable>
                                    <Pressable style={styles.item} onPress={replaceDevice}>
                                        <View style={styles.imgbox}>
                                            <FastImage
                                                style={styles.icons}
                                                source={{
                                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/7e152202502281147508257.png',
                                                    priority: FastImage.priority.high,
                                                }}
                                                resizeMode={FastImage.resizeMode.contain}
                                            />
                                        </View>
                                        <Text style={styles.title}>{t('AcupoinDeviceDetailes.t3')}</Text>
                                    </Pressable>
                                    <Pressable
                                        style={styles.item}
                                        onPress={() => navigation.navigate('DeviceSettings', { device_sn })}>
                                        <View style={styles.imgbox}>
                                            <FastImage
                                                style={styles.icons}
                                                source={require('~/assets/device/setting.png')}
                                                resizeMode={FastImage.resizeMode.contain}
                                            />
                                        </View>
                                        <Text style={styles.title}>{t('AcupoinDeviceDetailes.t28')}</Text>
                                    </Pressable>
                                </View>
                            </View>
                        ) : (
                            <View style={[styles.info]}>
                                <View style={[styles.row]}>
                                    <Pressable style={styles.item} onPress={reportData}>
                                        <View style={styles.imgbox}>
                                            <FastImage
                                                style={styles.icons}
                                                source={{
                                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/03/60d99202503051449269864.png',
                                                    priority: FastImage.priority.high,
                                                }}
                                                resizeMode={FastImage.resizeMode.contain}
                                            />
                                        </View>
                                        <Text style={styles.title}>{t('AcupoinDeviceDetailes.t8')}</Text>
                                    </Pressable>
                                    <Pressable style={styles.item} onPress={replaceWatch}>
                                        <View style={styles.imgbox}>
                                            <FastImage
                                                style={styles.icons}
                                                source={{
                                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/7e152202502281147508257.png',
                                                    priority: FastImage.priority.high,
                                                }}
                                                resizeMode={FastImage.resizeMode.contain}
                                            />
                                        </View>
                                        <Text style={styles.title}>{t('AcupoinDeviceDetailes.t3')}</Text>
                                    </Pressable>
                                </View>
                            </View>
                        )}
                    </View>
                    {parameterList.length > 0 &&
                        Array.isArray(parameterList) &&
                        yjhDevices.indexOf(deviceInfo.device_code) == -1 && (
                            <View style={[styles.card, { backgroundColor: 'none' }]}>
                                <Text style={styles.card_title}>{t('AcupoinDeviceDetailes.t12')}</Text>
                                <View style={[styles.courseDetailes, styles.row, styles.between]}>
                                    {parameterList.map((item: any, index) => {
                                        const result: any = getTitleAndContentByTime(item.start_time);
                                        return (
                                            <LinearGradient
                                                key={item?.id}
                                                style={styles.courseCard}
                                                colors={['#FFFFFF', '#E9FAF3']}
                                                start={{ x: 0, y: 0 }}
                                                end={{ x: 0, y: 1 }}>
                                                <View style={[styles.row, styles.between, { marginBottom: px2dp(24) }]}>
                                                    <Text style={styles.time}>{item?.start_time}</Text>
                                                    <Text style={styles.byTimeText}>{result?.content}</Text>
                                                </View>

                                                <View style={[styles.row, styles.between]}>
                                                    <Text style={styles.t3}>
                                                        {t('Acupoints.t20')}:{item?.course_name}
                                                    </Text>
                                                    <View style={[styles.active_border]}>
                                                        <Text style={[styles.active_border_text]}>
                                                            {item?.start_duration}
                                                            {t('Acupoints.t3')}
                                                        </Text>
                                                    </View>
                                                </View>
                                                {item?.course_name2 && (
                                                    <View
                                                        style={[styles.row, styles.between, { marginTop: px2dp(12) }]}>
                                                        <Text style={styles.t3}>
                                                            {t('Acupoints.t21')}:{item?.course_name2}
                                                        </Text>
                                                        <View
                                                            style={[
                                                                styles.active_border,
                                                                { backgroundColor: 'rgba(255, 100, 48, 0.12)' },
                                                            ]}>
                                                            <Text
                                                                style={[
                                                                    styles.active_border_text,
                                                                    { color: '#FF6430' },
                                                                ]}>
                                                                {item?.start_duration2 + t('Acupoints.t3')}
                                                            </Text>
                                                        </View>
                                                    </View>
                                                )}

                                                <View style={styles.line}></View>
                                                <Text style={styles.tips}>{item.desc}</Text>
                                            </LinearGradient>
                                        );
                                    })}
                                </View>
                            </View>
                        )}
                </ScrollView>
            </LinearGradient>
            <DialogModal
                visible={visible}
                content={t('AcupoinDeviceDetailes.t29')}
                onCancel={() => setVisible(false)}
                onConfirm={() => {
                    if (device_online == 1) {
                        startUpdate(device_sn);
                        setVisible(false);
                    } else {
                        Toast.show({ content: t('AcupoinDeviceDetailes.t30') });
                    }
                }}
            />
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    around: {
        justifyContent: 'space-around',
    },
    container: {
        flex: 1,
        backgroundColor: '#F7F7F7',
    },
    contentContainerStyle: {
        flexGrow: 1,
        paddingBottom: '30%',
        top: '14%',
    },
    deviceInfo: {
        width: width,
        alignSelf: 'center',
    },
    yy01: {
        width: px2dp(340),
        height: px2dp(340),
        alignSelf: 'center',
    },
    use_course_name: {
        color: '#111111',
        fontSize: scale(30),
        fontWeight: 'bold',
        marginTop: px2dp(24),
        textAlign: 'center',
    },
    device_sn: {
        color: '#111111',
        fontSize: scale(28),
        marginTop: px2dp(24),
        textAlign: 'center',
    },
    bindBt: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(29, 206, 135, 0.12)',
        height: px2dp(80),
        marginTop: px2dp(32),
        borderRadius: px2dp(12),
        width: px2dp(300),
        alignSelf: 'center',
    },
    bt_text: {
        color: '#1DCE87',
        fontSize: scale(28),
        fontWeight: 'bold',
    },
    card: {
        backgroundColor: '#fff',
        padding: px2dp(24),
        marginHorizontal: px2dp(24),
        marginTop: px2dp(32),
        borderRadius: px2dp(24),
    },
    card_title: {
        fontWeight: 'bold',
        fontSize: scale(28),
        color: '#1A1A1A',
    },
    info: {
        marginTop: px2dp(30),
    },
    item: {
        alignItems: 'center',
        justifyContent: 'center',
        width: (width - px2dp(96)) / 5,
    },
    icons: {
        width: px2dp(64),
        height: px2dp(64),
    },
    icons1: {
        width: px2dp(50),
        height: px2dp(50),
    },
    imgbox: {
        width: px2dp(70),
        height: px2dp(70),
        justifyContent: 'center',
        alignItems: 'center',
    },
    title: {
        color: '#4C4C4C',
        fontSize: scale(24),
        marginTop: px2dp(12),
        fontWeight: '400',
    },
    nav: {
        position: 'absolute',
        top: isIos() ? '8%' : '6%',
        justifyContent: 'space-between',
        width: width - px2dp(48),
        marginHorizontal: px2dp(24),
        zIndex: 999,
    },
    navtitle: {
        color: '#fff',
        fontSize: scale(30),
        fontWeight: 'bold',
    },
    courseDetailes: {
        flexWrap: 'wrap',
        marginTop: px2dp(12),
    },

    courseCard: {
        width: (width - px2dp(56)) / 2,
        backgroundColor: '#fff',
        padding: px2dp(24),
        borderRadius: px2dp(24),
        marginBottom: px2dp(12),
        height: px2dp(330),
        marginHorizontal: px2dp(-24),
    },
    time: {
        color: '#111111',
        fontWeight: '500',
        fontSize: scale(32),
    },
    byTimeText: {
        color: '#111111',
        fontWeight: '500',
        fontSize: scale(28),
    },
    tips: {
        fontWeight: '400',
        color: '#626262',
        fontSize: scale(28),
        lineHeight: px2dp(40),
    },
    t3: {
        fontSize: scale(22),
        color: '#666666',
        width: px2dp(200),
    },
    active_border: {
        backgroundColor: 'rgba(29, 206, 135, 0.12)',
        borderRadius: px2dp(12),
        marginLeft: px2dp(12),
        paddingHorizontal: px2dp(12),
        paddingVertical: px2dp(8),
    },
    active_border_text: {
        color: '#1DCE87',
        fontSize: scale(24),
    },
    line: {
        borderBottomWidth: onePx,
        borderColor: '#eee',
        marginVertical: px2dp(24),
    },
    version: {
        color: '#626262',
        fontSize: scale(26),
    },
    updateBt: {
        backgroundColor: '#3370FF',
        width: scale(180),
        height: px2dp(60),
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(50),
    },
});
